Skip to content

01 数据类型

Python 程序中的数据通常以不同类型存在。数字用于计算,字符串用于表示文本,列表用于保存一组有序数据。数字、字符串和列表是 Python 中最基础、最常用的几类数据类型。

一、数字

1.1 整数和浮点数

Python 的数字主要包括两种类型:int(整数)和float(浮点数)。

python
# 整数
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0

# 除法总是返回浮点数
>>> 8 / 5
1.6

1.2 整除和取余

//用于整除(丢弃小数部分),%用于取余数。

python
>>> 17 / 3    # 普通除法
5.666666666666667
>>> 17 // 3   # 整除
5
>>> 17 % 3    # 取余
2

1.3 幂运算

**用于计算幂次方。

python
>>> 5 ** 2    # 5的平方
25
>>> 2 ** 7    # 2的7次方
128

需要注意运算符优先级:-3**2等于-9(即-(3**2)),不是9。如果需要得到9,应写作(-3)**2

1.4 变量赋值

变量赋值使用=

python
>>> width = 20
>>> height = 5 * 9
>>> width * height
900

使用未定义变量会抛出错误:

python
>>> n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

1.5 其他数字类型

Python 还支持Decimal(精确小数)、Fraction(分数)和复数(3+5j)。

二、字符串

2.1 基本写法

字符串可以使用单引号或双引号包裹,两种写法效果相同。

python
>>> 'spam eggs'
'spam eggs'
>>> "Paris rabbit"
'Paris rabbit'

2.2 转义字符

字符串中的引号可以使用\转义,也可以通过更换外层引号避免转义。

python
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'

2.3 特殊字符

\n表示换行,\t表示制表符。交互式环境中直接显示字符串和使用print()输出的结果不同:

python
>>> s = 'First line.\nSecond line.'
>>> s
'First line.\nSecond line.'
>>> print(s)
First line.
Second line.

2.4 原始字符串

在引号前加r可以创建原始字符串,反斜杠不会被作为转义字符处理:

python
>>> print('C:\this\name')    # \t变成制表符
C:	his
ame
>>> print(r'C:\this\name')   # 原始字符串,原样输出
C:\this\name

2.5 多行字符串

三个引号可以用于编写多行字符串:

python
>>> print("""\
... Usage: thingy [OPTIONS]
...      -h                        Display this usage message
...      -H hostname               Hostname to connect to
... """)

示例第一行的\用于避免字符串开头多出一个空行。

2.6 字符串拼接和重复

python
>>> 3 * 'un' + 'ium'
'unununium'

相邻的字符串字面量会自动拼接:

python
>>> 'Py' 'thon'
'Python'

该自动拼接只适用于字符串字面量,不适用于变量:

python
>>> prefix = 'Py'
>>> prefix 'thon'   # 报错
SyntaxError: invalid syntax
>>> prefix + 'thon'  # 用+号
'Python'

2.7 索引和切片

字符串支持按位置取字符,第一个字符的索引为0

python
>>> word = 'Python'
>>> word[0]     # 第一个字符
'P'
>>> word[5]     # 最后一个字符
'n'
>>> word[-1]    # 倒数第一个
'n'
>>> word[-2]    # 倒数第二个
'o'

切片用于获取子字符串,范围采用左闭右开规则:

python
>>> word[0:2]   # 索引0到2(不含2)
'Py'
>>> word[2:5]   # 索引2到5(不含5)
'tho'
>>> word[:2]    # 从开头到2
'Py'
>>> word[4:]    # 从4到结尾
'on'
>>> word[-2:]   # 倒数两个
'on'

切片的起始位置会被包含,结束位置不会被包含。s[:i] + s[i:]始终等于s

2.8 字符串不可变

字符串创建后不可修改:

python
>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

如果需要得到修改后的内容,需要创建新字符串:

python
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'

2.9 len()函数

len()用于返回字符串长度:

python
>>> len('Python')
6
>>> len('supercalifragilisticexpialidocious')
34

三、列表

3.1 创建列表

列表使用方括号包裹,元素之间使用逗号分隔:

python
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

3.2 索引和切片

列表同样支持索引和切片:

python
>>> squares[0]
1
>>> squares[-1]
25
>>> squares[-3:]
[9, 16, 25]

3.3 列表可变

与字符串不同,列表是可变对象:

python
>>> cubes = [1, 8, 27, 65, 125]
>>> cubes[3] = 64   # 修改第4个元素
>>> cubes
[1, 8, 27, 64, 125]

3.4 添加元素

append()在末尾添加:

python
>>> cubes.append(216)
>>> cubes.append(7 ** 3)
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

3.5 赋值不复制数据

变量赋值会让两个变量绑定到同一个对象,并不会复制数据:

python
>>> rgb = ["Red", "Green", "Blue"]
>>> rgba = rgb
>>> rgba.append("Alph")
>>> rgb          # rgb也变了
["Red", "Green", "Blue", "Alph"]

如果需要复制列表,可以使用切片:

python
>>> correct_rgba = rgba[:]
>>> correct_rgba[-1] = "Alpha"
>>> correct_rgba
["Red", "Green", "Blue", "Alpha"]
>>> rgba         # 原来的不变
["Red", "Green", "Blue", "Alph"]

3.6 切片赋值

列表支持切片赋值,并且可以通过切片赋值改变列表长度:

python
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> letters[:] = []   # 清空列表
>>> letters
[]

3.7 嵌套列表

列表可以包含其他列表,形成嵌套结构:

python
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

3.8 len()函数

len()也适用于列表:

python
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

四、while循环

4.1 基本用法

while循环会在条件为真时重复执行:

python
>>> a, b = 0, 1
>>> while a < 10:
...     print(a)
...     a, b = b, a+b
...
0
1
1
2
3
5
8

4.2 多重赋值

a, b = 0, 1是多重赋值。右侧表达式会先全部计算,再同时赋值给左侧变量。

4.3 缩进

Python 使用缩进表示代码块,同一个代码块的缩进必须一致。常见约定是使用 4 个空格。

4.4 print()函数

print()用于输出内容。多个参数用逗号分隔时,会自动插入空格:

python
>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536

end参数可以修改输出结尾字符:

python
>>> a, b = 0, 1
>>> while a < 1000:
...     print(a, end=',')
...     a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

五、总结

类型特点用途
int整数计数、索引
float浮点数精确计算
str字符串,不可变文本处理
list列表,可变存储一组数据

常用操作:

操作说明
s[i]索引取值
s[i:j]切片
s + t拼接
s * n重复
len(s)长度
s.append(x)列表末尾添加
s[i] = x列表修改(字符串不行)

数字、字符串和列表是 Python 基础语法中最常用的数据类型,后续语法和标准库内容都建立在这些基础类型之上。